package com.lepu.pcecg500.util;

import android.content.Context;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;
import com.net.util.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * author : xiaoxin
 * date   : 2020/10/26 20:32
 * desc   :
 * update :
 */
public class FileUtils {

    public static final String LOG_PATH = Environment.getExternalStorageDirectory()+"/bloodsugar/logCrash/";
    public static final String PATH_ROOT = Environment.getExternalStorageDirectory()+"/bloodsugar/";
    public static final String PATH_ROOT_ECG = Environment.getExternalStorageDirectory()+"/bloodsugar/ecg/";

    /**
     * 拷贝数据库文件
     * @param context 上下文
     * @param db 数据库文件名
     */
    public static void copyAddressDB(final Context context, final String path, final String db) {
        File filePath = new File(path);
        File file = new File(path,db);
        if (!filePath.exists()) {
            filePath.mkdir();
        }
        if(file.exists() && file.length() > 0) {
            LogUtils.e( "数据库存在无需拷贝" + db);
        }else {
            new Thread() {
                public void run() {
                    //把assets里面的数据库文件拷贝到手机系统里面
                    try {
                        InputStream is = context.getAssets().open(db);
                        File file = new File(path,db);
                        FileOutputStream fos = new FileOutputStream(file);

                        LogUtils.e("数据库路径地址：" + path + db);
                        byte[] b = new byte[1024];
                        int len = -1;
                        while((len = is.read(b))!=-1) {
                            fos.write(b, 0, len);
                        }
                        is.close();
                        fos.close();
                        LogUtils.e( "拷贝成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                        LogUtils.e(e.getMessage());
                    }
                }
            }.start();
        }
    }

    /**
     * 检查路径是否存在
     */
    public static void isPathExist() {

        File rootFile = new File(PATH_ROOT) ;
        if(!rootFile.exists()){
            rootFile.mkdirs() ;
        }

        File logFile = new File(LOG_PATH);
        if(!logFile.exists()){
            logFile.mkdirs() ;
        }

        File ECGFile = new File(PATH_ROOT_ECG);
        if(!ECGFile.exists()){
            ECGFile.mkdirs() ;
        }

    }

}
